// 品牌管理控制器
const Brand = require('../../models/product/brand.model');
const sendResponse = require('../../utils/response');

// 获取品牌列表
exports.getTrademarkList = async (req, res, next) => {
  try{
    // 获取分页参数
    const page = parseInt(req.params.page, 10) || 1;
    const limit = parseInt(req.params.limit, 10) || 10;
    // 计算偏移量
    const offset = (page - 1) * limit;
    const trademark = await Brand.findAndCountAll({
      limit,
      offset,
      order: [['id', 'DESC']],
      attributes: ['id', 'tmName', 'logoUrl']
    });
    console.log("------获取品牌列表成功-------");
    return sendResponse(res, { message: '获取品牌列表成功', data: {
      records: trademark.rows,
      total: trademark.count, // 总条数
      size: limit,
      current: page,
      pages: Math.ceil(trademark.count / limit)
    }})
  } catch (error) {
    next(error)
  }
}

// 获取全部品牌
exports.getAllTrademark = async (req, res, next) => {
  try {
    const trademark = await Brand.findAll({
      order: [['id', 'DESC']],
      attributes: ['id', 'tmName', 'logoUrl']
    });
    console.log("------获取全部品牌成功-------");
    
    return sendResponse(res, { message: '获取品牌列表成功', data: trademark })
  } catch (error) {
    next(error)
  }
}

// 添加品牌
exports.addTrademark = async (req, res, next) => {
  try {
    const { tmName, logoUrl } = req.body;
    if(!tmName && !logoUrl){
      return sendResponse(res, { code: 500, message: '参数错误' })
    }
    console.log("------添加品牌参数-------", tmName, logoUrl);
    
    const trademark = await Brand.create({
      tmName,
      logoUrl: logoUrl.url || logoUrl
    });
    console.log("------添加品牌成功-------");
    
    return sendResponse(res, { message: '添加品牌成功', data: trademark })
  } catch (error) {
    next(error)
  }
}

// 删除品牌
exports.removeTrademark = async (req, res, next) => {
  try {
    const { id } = req.params;
    // 检测id是否存在
    const trademark = await Brand.findOne({
      where: {
        id
      }
    });
    if (!trademark) return sendResponse(res, { code: 500, message: '品牌不存在' });
    // 删除品牌
    await Brand.destroy({
      where: {
        id
      }
    });
    console.log("------删除品牌成功-------");
    return sendResponse(res, { message: '删除品牌成功' })
  } catch (error) {
    next(error)
  }
}

// 更新品牌
exports.updateTrademark = async (req, res, next) => {
  try {
    const { id, tmName, logoUrl } = req.body;
    // 检测参数是否正确
    if (isNaN(id) || !tmName || !logoUrl) return sendResponse(res, { code: 500, message: '参数错误' });
    // 更新品牌
    await Brand.update({
      tmName,
      logoUrl
    }, {
      where: {
        id
      }
    });
    console.log("------更新品牌成功-------");
    
    return sendResponse(res, { message: '更新品牌成功' })
  } catch (error) {
    next(error)
  }
}
